import { NETWORK_DISK_TYPE } from '@/utils/enum'
import lodash from 'lodash'
import {
  getAliPanData, getDownloadLink,
  getDuPanFileListLogic,
  getFileDetail,
  getFileDetailLogic,
  getVideoStreaming,
  handleFileDownloadLogic
} from '@/api/aliPan'

const timer = null
export const LEFT_FILE_LIST = {
  [NETWORK_DISK_TYPE.INDEX_BAIDU.type]: {
    handlePotPlayer: async(payload, _that) => {
      // downloadByLink('potplayer://' + payload.dlink)

      let adInfo = {}
      await getVideoStreaming({ path: encodeURI(_that.filePreview.path) }).then((res) => {
        if (res.code === 0) {
          adInfo = res.data
        }
      })
      if (_that.timer) {
        clearInterval(_that.timer)
        // eslint-disable-next-line require-atomic-updates
        _that.timer = null
      }
      let time = adInfo.ltime
      if (adInfo.errno === 133) {
        time = adInfo.adTime
      }
      // eslint-disable-next-line require-atomic-updates

      // eslint-disable-next-line require-atomic-updates
      _that.timer = setInterval(() => {
        if (_that.filePreview && _that.filePreview.path) {
          getVideoStreaming({ path: encodeURI(_that.filePreview.path), adToken: adInfo.adToken }).then((res) => {
            // eslint-disable-next-line no-empty
            if (typeof res === 'string') {
              const blob = new Blob([res], { type: 'text/plain' })
              // 创建一个下载链接
              const downloadLink = document.createElement('a')
              // 设置下载链接的属性
              downloadLink.href = window.URL.createObjectURL(blob)
              if (_that.filePreview && downloadLink) {
                _that.filePreview.url = downloadLink.href
                downloadLink.download = `${_that.filePreview.name}.m3u8`
                downloadLink.textContent = 'Download File'
                // 将链接添加到页面中
                document.body.appendChild(downloadLink)
                // 模拟点击下载链接
                downloadLink.click()
                // 移除下载链接
                document.body.removeChild(downloadLink)
              }

              clearInterval(_that.timer)
            } else {
              adInfo.adToken = res.data.adToken
            }
          })
        }
      }, (time) * 1000)
    },
    getFileDetail: function(payload, _that, root) {
      // fsids
      if (!payload.fileId || payload.isdir) {
        // root.getRootList(payload, _that, root)
        if (_that.updateCenterData) {
          _that.updateCenterData(payload)
        } else {
          _that.$emit('updateCenterData', payload)
        }
        return
      }
      getDuPanFileDetailLogic(_that, payload)
    },
    getMediaCover(item) {
      if (item.thumbs) return item.thumbs.url1
      if (item.category === 2) return 'https://pan.rawchen.com/static/img/type/music.png'
      if (item.category === 6 && item.isdir === 0) return 'https://pan.rawchen.com/static/img/type/compress.png'
      return 'https://pan.rawchen.com/static/img/folder.jpg'
    },
    getRootList(payload, _that, root) {
      //
      if (!payload.isdir) {
        getDuPanFileDetailLogic(_that.$refs.mainContent, payload)
        return
      }

      // const loading = _that.$loading({})
      _that.fullFileIdArr = _that.fullFileIdArr.concat([{ ...payload }])
      getDuPanFileListLogic({ dir: payload.path, password: payload && payload.password }).then((res) => {
        updateDuCenterData(_that, res, payload)
      }).finally(() => {
        //loading.close()
      })
    },
    name: NETWORK_DISK_TYPE.INDEX_BAIDU.name,
    root: NETWORK_DISK_TYPE.INDEX_BAIDU.type,
    type: NETWORK_DISK_TYPE.INDEX_BAIDU.type,
    getParentFileDetail(payload, _that) {
      // const loading = _that.$loading({})
      getDuPanFileListLogic({ dir: payload.parent_dir }).then((res) => {
        updateDuCenterData(_that, res, payload)
        _that.fullFileIdArr.pop()
      }).finally(() => {
        //loading.close()
      })
    },
    isdir: true,
    handleFileDownloadLogic(payload, _that) {
      if (payload.size > 50 * 1024 * 1024) {
        _that.$message.error('百度网盘不支持下载超过50MB的文件')
        return
      }

      // 获取下载链接
      _that.downLoading = true
      getDownloadLink({ dlink: payload.dlink }).then((res) => {
        // https://blog.csdn.net/weixin_43550766/article/details/121991772
        const url = window.URL.createObjectURL(res)
        const fileName = payload.name
        downloadByLink(url, fileName)
        _that.downLoading = false
      })
    }
  },
  [NETWORK_DISK_TYPE.INDEX_ALI.type]: {
    handlePotPlayer: function(payload, _that) {
      // const loading = _that.$loading({})
      handleFileDownloadLogic({ drive_id: payload.drive_id, file_id: payload.file_id }).then((res) => {
        if (res.code === 0) {
          downloadByLink('potplayer://' + res.data.url)
        } else {
          _that.$message.error('下载失败')
        }
      }).finally(() => {
        //loading.close()
      })
    },
    handleFileDownloadLogic(payload, _that) {
      // const loading = _that.$loading({})
      handleFileDownloadLogic({ drive_id: payload.drive_id, file_id: payload.file_id }).then((res) => {
        if (res.code === 0) {
          downloadByLink(res.data.url)
        } else {
          _that.$message.error('下载失败')
        }
      }).finally(() => {
        //loading.close()
      })
    },
    isdir: true,
    name: NETWORK_DISK_TYPE.INDEX_ALI.name,
    type: NETWORK_DISK_TYPE.INDEX_ALI.type,
    root: NETWORK_DISK_TYPE.INDEX_ALI.type,
    getRootList(payload, _that) {
      // 如果是文件
      if (payload.type === 'file') {
        // _that指向home
        getFileDetailLocal(_that.$refs.mainContent, payload).then(r => {})
        return
      }
      // const loading = _that.$loading({})
      const { file_id, drive_id } = payload
      _that.fullFileIdArr = _that.fullFileIdArr.concat([payload])
      getAliPanData({ file_id, drive_id, password: payload && payload.password }).then((res) => {
        updateCenterData(_that, res, payload)
      }).finally(() => {
        //loading.close()
      })
    },
    async getFileDetail(item, _that, root) {
      if (!item.file_id || item.type === 'folder') {
        if (_that.updateCenterData) {
          _that.updateCenterData(item)
        } else {
          _that.$emit('updateCenterData', item)
        }
        return
      }

      await getFileDetailLocal(_that, item)
    },
    getParentFileDetail(payload, _that) {
      // const loading = _that.$loading({})
      getAliPanData({ file_id: payload.parent_file_id, drive_id: payload.drive_id }).then((res) => {
        updateCenterData(_that, res, payload)
        _that.fullFileIdArr.pop()
      }).finally(() => {
        //loading.close()
      })
    }
  }
}

export function makeNetworkDiskConfig() {
  return lodash.cloneDeep(LEFT_FILE_LIST)
}

// eslint-disable-next-line no-unused-vars
function handleReset(_that) {
  if (_that.mainData) _that.mainData = []
  if (_that.fileNeedPassword) _that.fileNeedPassword = null
  if (_that.filePreview) _that.filePreview = null
}

function updateCenterData(_that, res, payload) {
  if (_that.$refs.mainContent) {
    _that.$refs.mainContent.resetFile()
  }
  // handleReset(_that)
  if (res.code === 0) {
    if (res.data.items) {
      _that.mainData = res.data.items
      if (_that.mainData.length === 0) {
        _that.$message.warning('该文件夹没有文件哦~')
      }
      _that.mainData.forEach(item => {
        item.root = NETWORK_DISK_TYPE.INDEX_ALI.type
      })
      // 将获取的目录类型的取出
      // const folderList = _that.mainData.filter(item => item.category === null)
      if (!payload.children && (payload.type === 'folder' || payload.type === 1)) {
        _that.$set(payload, 'children', _that.mainData)
      } else {
        _that.$set(payload, 'children', null)
      }
    } else {
      _that.$message.error(res.data.message)
    }
  } else if (res.code === 405) {
    _that.fileNeedPassword = payload
  } else {
    _that.$message.error(res.msg)
  }
}

function updateDuCenterData(_that, res, payload) {
  if (_that.$refs.mainContent) {
    _that.$refs.mainContent.resetFile()
  }
  if (res.code === 0) {
    if (res.data.list) {
      _that.mainData = res.data.list.map(item => ({
        name: item.server_filename,
        category: item.category,
        fileId: item.fs_id,
        rootName: NETWORK_DISK_TYPE.INDEX_BAIDU.name,
        root: NETWORK_DISK_TYPE.INDEX_BAIDU.type,
        ...item,
        parent_file_id: payload.fs_id,
        parent_dir: payload.path
      }))
      if (_that.mainData.length === 0) {
        _that.$message.warning('该文件夹没有文件哦~')
      }
      // 将获取的目录类型的取出
      // const folderList = _that.mainData.filter(item => item.category === 6)
      const folderList = _that.mainData
      folderList.forEach(item => {
        item.root = NETWORK_DISK_TYPE.INDEX_BAIDU.type
        item.parent_file_id = payload.fs_id
      })
      if (!payload.children && payload.isdir) {
        _that.$set(payload, 'children', folderList)
      } else {
        _that.$set(payload, 'children', null)
      }
    } else {
      _that.$message.error(res.data.message)
    }
  } else if (res.code === 405) {
    _that.fileNeedPassword = payload
    console.log(res.code === 405)
  } else {
    _that.$message.error(res.msg)
  }
}

async function getFileDetailLocal(_that, item) {
  // 预览文件了
  if (_that) {
    _that.$emit('update:fullFileIdArr', _that.fullFileIdArr.concat([item]))
  }

  // handleReset(_that)

  if (_that.resetFile) {
    _that.resetFile()
  }
  // const loading = _that.$loading({})
  await getFileDetail(item).then((res) => {
    if (res.code === 0 && res.data) {
      // 图片
      _that.filePreview = res.data
      _that.filePreview.root = item.root
      _that.$store.commit('setStoreValue', { filePreview: _that.filePreview })
      // 视频
      _that.$nextTick(() => {
        if (_that.dp) _that.dp.destroy()
        _that.initDPlayer()
      })
    }
  }).finally(() => {
  })
  // 代码
  if (_that.filePreview.category === 'others') {
    await _that.getBinaryData(_that.filePreview.url)
  }
  //loading.close()
}

function getDuPanFileDetailLogic(_that, payload) {
  // const loading = _that.$loading({})
  _that.$emit('update:fullFileIdArr', _that.fullFileIdArr.concat([payload]))
  getFileDetailLogic({ fileId: payload.fileId }).then(async(res) => {
    if (res.code === 0 && res.data) {
      _that.filePreview = res.data.list[0]
      _that.$store.commit('setStoreValue', { filePreview: _that.filePreview })
      const { filename, category, dlink } = _that.filePreview
      _that.filePreview.name = filename
      _that.filePreview.root = payload.root
      // _that.filePreview.parent_dir = '/'
      // _that.filePreview.url = dlink
      // 获取下载链接
      // getDownloadLink({ dlink: dlink }).then((res) => {
      //   console.log(res)
      //
      // })
      // 视频
      if (_that.filePreview.category === 1) {
        let adInfo = {}
        await getVideoStreaming({ path: encodeURI(_that.filePreview.path) }).then((res) => {
          if (res.code === 0) {
            adInfo = res.data
          }
        })
        if (_that.timer) {
          clearInterval(_that.timer)
          // eslint-disable-next-line require-atomic-updates
          _that.timer = null
        }
        let time = adInfo.ltime
        if (adInfo.errno === 133) {
          time = adInfo.adTime
        }
        // eslint-disable-next-line require-atomic-updates

        // eslint-disable-next-line require-atomic-updates
        _that.timer = setInterval(() => {
          if (_that.filePreview && _that.filePreview.path) {
            // getVideoStreaming({ path: encodeURI(_that.filePreview.path), adToken: adInfo.adToken }).then((res) => {
            //   // eslint-disable-next-line no-empty
            //   if (typeof res === 'string') {
            //     const blob = new Blob([res], { type: 'text/plain' })
            //     // 创建一个下载链接
            //     const downloadLink = document.createElement('a')
            //     // 设置下载链接的属性
            //     downloadLink.href = window.URL.createObjectURL(blob)
            //     if (_that.filePreview && downloadLink) {
            //       _that.filePreview.url = downloadLink.href
            //       downloadLink.download = `${_that.filePreview.name}.m3u8`
            //       downloadLink.textContent = 'Download File'
            //       // 将链接添加到页面中
            //       document.body.appendChild(downloadLink)
            //       // 模拟点击下载链接
            //       downloadLink.click()
            //       // 移除下载链接
            //       document.body.removeChild(downloadLink)
            //     }
            //
            //     clearInterval(_that.timer)
            //   } else {
            //     adInfo.adToken = res.data.adToken
            //   }
            // })
          }
        }, (time) * 1000)
      } else {
        _that.filePreview.url = dlink
      }

      // 文件代码
      if (_that.filePreview.category === 4) {
        await _that.getBinaryData(_that.filePreview.url)
      }

      //loading.close()
      // axios({
      //   url: dlink,
      //   method: 'GET',
      //   headers: {
      //     'User-Agent': 'pan.baidu.com'
      //   }
      // }).then((res) => {
      //   console.log(res)
      // })
      // 视频
      _that.$nextTick(() => {
        if (_that.dp) _that.dp.destroy()
        _that.initDPlayer()
      })
    }
  })
}

export function downloadByLink(url, fileName) {
  const downloadLink = document.createElement('a')
  // 设置下载链接的属性
  downloadLink.href = url
  downloadLink.download = fileName
  downloadLink.textContent = 'Download File'
  // 将链接添加到页面中
  document.body.appendChild(downloadLink)
  // 模拟点击下载链接
  downloadLink.click()
  // 移除下载链接
  document.body.removeChild(downloadLink)
}
